//
//  LoginViewModel.m
//  Yihubang
//
//  Created by hyu on 16/7/29.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "PreLoginViewModel.h"
#import "UMSocial.h"
#import "UserAgreementVC.h"
#import "AlterSecurityCideViewController.h"
//#import "NewsClueNav.h"
@interface PreLoginViewModel ()<checkPasswordSuccessDelegate>
@property (nonatomic, strong, readwrite) NSString *phoneCodeText;
@property (nonatomic, strong, readwrite) RACSignal *validLoginSignal;
@property (nonatomic, strong, readwrite) RACSignal *getCodeSignal;
@property (nonatomic, strong, readwrite) RACCommand *loginCommand;
@property (nonatomic, strong, readwrite) RACCommand *otherLoginCommand;
@property (nonatomic, strong, readwrite) RACCommand *phoneCodeCommand;
@property (nonatomic, strong, readwrite) RACCommand *autoLoginCommand;
@property (nonatomic, strong, readwrite) RACCommand *nextCommand;
@property (nonatomic,strong)NSNumber *littleTime ;
@property (nonatomic,strong)NSTimer *codeTimer ;
@property (nonatomic,strong)NSTimer *updateSelfInfoTimer ;

@property (nonatomic, strong, readwrite) RACCommand *ceshi;
@property (nonatomic, strong, readwrite) RACCommand *userAgreement;
@end

@implementation PreLoginViewModel

- (void)initialize {
    [super initialize];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(stopTimerToUpdate) name:@"stopTimerToUpdate" object:nil];
    
    @weakify(self)
    
    //
    //    self.ceshi = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    //        @strongify(self);
    //        [[self.httpService deleteContact:@"郭" resultClass:nil] subscribeNext:^(BaseModel *model) {
    //            @strongify(self);
    //            [self startTimer];
    //            if (model.code == 200) {
    //
    //            }else {
    //                [self showRequestErrorMessage:model];
    //            }
    //        }error:^(NSError *error) {
    //            [self.viewController hiddenHUDWithString:@"网络链接差，请稍后再试" error:NO];
    //        }completed:^{
    //
    //        }];
    //        return [RACSignal empty];
    //    }];
    
    self.phoneCodeText =@"发送验证码";
    //账号密码的长度必须都大于0
    self.validLoginSignal = [[RACSignal
                              combineLatest:@[ RACObserve(self, telePhoneStr), RACObserve(self, codeStr)]
                              reduce:^(NSString *username, NSString *password) {
                                  return @(username.length == 11 && password.length ==4 );
                              }]
                             distinctUntilChanged];
    self.getCodeSignal = [[RACSignal
                           combineLatest:@[RACObserve(self, telePhoneStr), RACObserve(self, littleTime) ]
                           reduce:^(NSString *phone, NSNumber *littleTime) {
                               return @(phone.length == 11 && littleTime.intValue <= 0);
                           }]
                          distinctUntilChanged];
    
    self.loginSuccessCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSDictionary * input) {
        @strongify(self)
        [self uploadLogString];
        [self initAppConfig];
        [self stopTimer];
        return [RACSignal empty];
    }];
    //    self.autoLoginSuccessCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    //        @strongify(self)
    //        [self uploadLogString];
    //        [self initAppConfig];
    //        [self stopTimer];
    //        return [RACSignal empty];
    //    }];
    
    
    self.loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self)
        [self.viewController.view endEditing:NO];
        [self.viewController showHUDWithString:@"登录中..."];
        @weakify(self)
        [[self.httpService loginByPhone:self.telePhoneStr code:self.codeStr resultClass:nil] subscribeNext:^(BaseModel *model) {
            @strongify(self);
            if (model.code==200) {
                [[UserClient sharedUserClient] setUserName:self.telePhoneStr password:model.data[@"password"]];
                [[UserClient sharedUserClient] setLoginType:MasterLoginType_Phone];
                [[UserClient sharedUserClient] setUserLoginInfo:model.data];
                [[UserClient sharedUserClient] setUserInfo:model.data];
                [self updateSelfInfoTimer];
                [self.viewController hiddenHUDWithString:@"登录成功" error:NO];
                [self.loginSuccessCommand execute:model.data];
            }else {
                [self.viewController hiddenHUDWithString:model.message error:YES];
                [self showRequestErrorMessage:model];
                if (self.loginErrorCommand) {
                    [self.loginErrorCommand execute:nil];
                }
            }
            NSLog(@"====1 %@",model.message);
            
        } error:^(NSError *error) {
            NSLog(@"====1 %@",error);
            [self.viewController hiddenHUDWithString:@"登录失败，请检查网络连接" error:NO];
        } completed:^{
            @strongify(self)
            [self.viewController hiddenHUD];
        }] ;
        return [RACSignal empty];
    }];
    //手机号自动登录
    self.autoLoginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self)
        [self.viewController.view endEditing:NO];
        //        [self.viewController showHUDWithString:@"登录中..."];
        [[self.httpService autologinByPhone:self.telePhoneStr SecurityCode:self.codeStr resultClass:nil] subscribeNext:^(BaseModel *model) {
            @strongify(self);
            if (model.code==200) {
                [[UserClient sharedUserClient] setUserName:self.telePhoneStr password:model.data[@"password"]];
                [[UserClient sharedUserClient] setLoginType:MasterLoginType_Phone];
                [[UserClient sharedUserClient] setUserLoginInfo:model.data];
                [[UserClient sharedUserClient] setUserInfo:model.data];
                //                [self.viewController hiddenHUDWithString:@"登录成功" error:NO];
                [self updateSelfInfoTimer];
                [self.loginSuccessCommand execute:model.data];
                //                [self uploadLogString];
            }else {
                //                                [self.viewController hiddenHUDWithString:model.message error:YES];
                [self showRequestErrorMessage:model];
                if (self.loginErrorCommand) {
                    [self.loginErrorCommand execute:nil];
                }
            }
            NSLog(@"====1 %@",model.message);
            
        } error:^(NSError *error) {
            NSLog(@"====1 %@",error);
            [SharedAppDelegate openAppMainVCT];
        } completed:^{
            @strongify(self)
            [self.viewController hiddenHUD];
        }] ;
        return [RACSignal empty];
    }];
    
    //发送验证码
    self.phoneCodeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        [[self.httpService sendPhoneCode:self.telePhoneStr resultClass:nil] subscribeNext:^(BaseModel *model) {
            @strongify(self);
            [self startTimer];
            if (model.code==200) {
                //                self.codeStr = model.data[@"code"];
                //                [self.viewController hiddenHUDWithString:model.data[@"code"] error:NO];
                //                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"验证码"
                //                                                                    message:model.data[@"code"]
                //                                                                   delegate:self
                //                                                          cancelButtonTitle:@"知道了" otherButtonTitles: nil];
                //                [alertView show];
                
            }else{
                [self showRequestErrorMessage:model];
            }
        } error:^(NSError *error) {
            [self.viewController hiddenHUDWithString:@"网络链接差,请稍候在试." error:NO];
        } completed:^{
            
        }];
        
        return [RACSignal empty];
    }];
    
    self.otherLoginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(UMSocialAccountEntity *input) {
        @strongify(self)
        [self.viewController.view endEditing:NO];
        [self.viewController showHUDWithString:@"登录中..."];
        NSString * unionId;
        if([UserClient sharedUserClient].loginType ==MasterLoginType_Weixin){
            unionId =input.unionId ? input.unionId:[UserClient sharedUserClient].unionId;
        }else{
            unionId =input.unionId;
        }
        [[self.httpService otherLoginByPlatform:input.platformName uid:input.usid unionId:unionId nickname:input.userName iconUrl:input.iconURL gender:@"1" resultClass:nil] subscribeNext:^(BaseModel *model) {
            @strongify(self)
            if (model.code==200) {
                [[UserClient sharedUserClient] setLoginTypeName:input.platformName];
                [[UserClient sharedUserClient] setUserName:model.data[@"mobile"] password:model.data[@"password"]];
                [[UserClient sharedUserClient] setUserLoginInfo:model.data];
                [[UserClient sharedUserClient] setUserInfo:model.data];
                [[UserClient sharedUserClient] setUnionId:input.unionId];
                [self.viewController hiddenHUDWithString:@"登陆成功" error:NO];
                [self updateSelfInfoTimer];
                [self.loginSuccessCommand execute:model.data];
                [self uploadLogString];
                
            }else {
                [self showRequestErrorMessage:model];
                if (self.loginErrorCommand) {
                    [self.loginErrorCommand execute:nil];
                }
            }
        } error:^(NSError *error) {
            
        } completed:^{
        }];
        
        return [RACSignal empty];
    }];
    
    
    //    // 新2017-6-13
    //    // 进入下一步发送验证码
    //    self.nextCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    //        @strongify(self);
    //        [[self.httpService sendPhoneCode:self.telePhoneStr resultClass:nil] subscribeNext:^(BaseModel *model) {
    //            @strongify(self);
    //            [self startTimer];
    //            if (model.code == 200) {
    //
    //            }else{
    //                [self showRequestErrorMessage:model];
    //            }
    //        } error:^(NSError *error) {
    //            [self.viewController hiddenHUDWithString:@"网络链接差,请稍后再试" error:NO];
    //        } completed:^{
    //
    //        }];
    //        return [RACSignal empty];
    //    }];
    
    self.userAgreement = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"LoginTo" bundle:[NSBundle mainBundle]];
        UIViewController *vc = [story instantiateViewControllerWithIdentifier:@"UserAgreementVC"];
        [self.viewController.navigationController pushViewController:vc animated:YES];
        return [RACSignal empty];
    }];
    
    //    self.validLoginSignal = [[RACSignal
    //                              combineLatest:@[ RACObserve(self, telePhoneStr), RACObserve(self, codeStr) ]
    //                              reduce:^(NSString *username, NSString *password) {
    //                                  return @(username.length == 11 && password.length !=4);
    //                              }]
    //                             distinctUntilChanged];
    
    //    // 监测手机号输入的位数是否为11位
    //    self.validLoginSignal = [RACObserve(self, telePhoneStr) map:^id(NSString *username) {
    //        return @(username.length == 11);
    //    }];
    //
    //
    //    self.getCodeSignal = [[RACSignal
    //                           combineLatest:@[RACObserve(self, telePhoneStr), RACObserve(self, littleTime) ]
    //                           reduce:^(NSString *phone, NSNumber *littleTime) {
    //                               return @(phone.length == 11 && littleTime.intValue <= 0);
    //                           }]
    //                          distinctUntilChanged];
    
    
    
}

- (void)uploadLogString{
    HttpManagerCenter* httpCenter = [HttpManagerCenter sharedHttpManager];
    if (UserBehaviourKey) {
        
        [[httpCenter uploadLogString:[[NSUserDefaults standardUserDefaults] objectForKey:UserBehaviourKey] resultClass:nil] subscribeNext:^(BaseModel *model) {
            if(model.code==200){
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:UserBehaviourKey];
                NSLog(@"日志上传成功");
            }
        }];
    }
}

//- (void)initAppConfig:(NSInteger)type {
//    if(type ==1){
//        UIViewController *vct;
//        vct = [UIViewController viewControllerWithStoryboard:@"GuardMe" identifier:@"DeterrenceVC" ];
//        [self.viewController.navigationController pushViewController:vct animated:NO];
//
//    }
//}

- (void)initAppConfig{
    HttpManagerCenter* httpCenter = [HttpManagerCenter sharedHttpManager];
    [[httpCenter appConfig:nil] subscribeNext:^(BaseModel *model) {
        NSLog(@"%@",model.data);
        if (model.code == 200) {
            NSDictionary *data = model.data[@"emergency"];
            if ([data count]) {
                [[UserClient sharedUserClient] setOpenTypeStatus:@[@"2", model.data[@"emergency"][0][@"id"]]];
            }
        }
        if([self.viewController.userClient.userLoginInfo[@"sex"] isEqualToString:@"0"]){
            
            /* 新用户注册登录  跳转输入安全密码 */
            //            [[NSUserDefaults standardUserDefaults] setObject:@"NoFrist" forKey:TestFristKey];
            UIStoryboard *story = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
            UIViewController *myView = [story instantiateViewControllerWithIdentifier:@"AlterSecurityCideViewController"];
            myView.params =@{@"identity":@"login"};
            [self.viewController.navigationController pushViewController:myView animated:YES];
            
            
        }else{
            
            [SharedAppDelegate openAppMainVCT];
        }
        
    }];
}
- (NSTimer*)startTimer{
    if (!_codeTimer) {
        self.littleTime = [NSNumber numberWithInt:60];
        _codeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
    }
    return _codeTimer;
}
- (NSTimer*)updateSelfInfoTimer{
    if (!_updateSelfInfoTimer) {
        _updateSelfInfoTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(updateSelfInfo) userInfo:nil repeats:YES];
    }
    return _updateSelfInfoTimer;
}
- (void)changeTimeAtTimedisplay{
    self.littleTime = [NSNumber numberWithInt:self.littleTime.intValue-1];
    if (self.littleTime.intValue==0) {
        self.phoneCodeText = @"发送验证码";
        [self stopTimer];
    }else{
        self.phoneCodeText = [NSString stringWithFormat:@"%@ s",self.littleTime];
    }
}
- (void)updateSelfInfo{
    [[[HttpManagerCenter sharedHttpManager] update_baseInfoWithResultClass:nil]subscribeNext:^(BaseModel *model) {
        if(model.code ==200){
            if ([model.data[@"help"] integerValue] > 0 || [model.data[@"my_help"] integerValue] > 0) {
                [KGlobalView sharedKGlobalView].imageView.image = [UIImage imageNamed:@"有通知"];
                if ([model.data[@"my_help"] integerValue] > 0) {
                    [[KGlobalView sharedKGlobalView].showMarkParams replaceObjectAtIndex:0 withObject:@(0)];
                }else{
                    [[KGlobalView sharedKGlobalView].showMarkParams replaceObjectAtIndex:0 withObject:@(1)];
                }
                if ([model.data[@"help"] integerValue] > 0) {
                    [[KGlobalView sharedKGlobalView].showMarkParams replaceObjectAtIndex:1 withObject:@(0)];
                }else{
                    [[KGlobalView sharedKGlobalView].showMarkParams replaceObjectAtIndex:1 withObject:@(1)];
                }
            }else{
                [KGlobalView sharedKGlobalView].imageView.image = [UIImage imageNamed:@"通知"];
                [[KGlobalView sharedKGlobalView].showMarkParams replaceObjectAtIndex:0 withObject:@(1)];
                [[KGlobalView sharedKGlobalView].showMarkParams replaceObjectAtIndex:1 withObject:@(1)];
            }
        }
    }];//60s更新用户信息
}
- (void)stopTimer{
    if (_codeTimer) {
        [_codeTimer invalidate];
    }
    _codeTimer = nil;
}
-( void)stopTimerToUpdate{
    if (_updateSelfInfoTimer) {
        [_updateSelfInfoTimer invalidate];
    }
    _updateSelfInfoTimer = nil;
}
- (void)dealloc{
    [self stopTimer];
}
@end

